/**
 * @author 雷明浩
 * @date 2025/5/30 14:31
 */
public class KthSmallest {
    // leetcode 二叉搜索树中第k小的元素
    // https://leetcode.cn/problems/kth-smallest-element-in-a-bst/?envType=study-plan-v2&envId=top-100-liked
    private int count;
    public int kthSmallest(TreeNode root, int k) {
        count = k;
        return kthSmallestChild(root);
    }

    private int kthSmallestChild(TreeNode root) {
        if (root == null) {
            return -1;
        }
        int leftIndex = kthSmallestChild(root.left);
        if (leftIndex != -1) {
            return leftIndex;
        }
        count--;
        if (count == 0) {
            return root.val;
        }
        return kthSmallestChild(root.right);
    }
}